package com.liuxm.es.test;

import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.Avg;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

/**
 * @author liuxm
 * @version 1.0
 * @date 2021/3/19 21:03
 */
public class DocumentAggregation {

    RestHighLevelClient client;
    private Aggregations aggregations;

    @Before
    public void before() {
        client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("192.168.31.11", 9200, "http")
                )
        );
    }

    @After
    public void after() throws IOException {
        client.close();
    }

    /**
     * 按照性别分组
     * 求每个小组的平均年龄
     *
     * @throws IOException
     */
    @Test
    public void genderAvgAge() throws IOException {
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        TermsAggregationBuilder terms_by_gender = AggregationBuilders.terms("terms_by_gender").field("gender");
        AvgAggregationBuilder avg_by_age = AggregationBuilders.avg("avg_by_age").field("age");
        terms_by_gender.subAggregation(avg_by_age);
        sourceBuilder.aggregation(terms_by_gender);

        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        Terms terms_by_gender_result = searchResponse.getAggregations().get("terms_by_gender");
        for (Terms.Bucket bucket : terms_by_gender_result.getBuckets()) {
            String keyAsString = bucket.getKeyAsString();
            long docCount = bucket.getDocCount();
            Avg avg_by_age_result = bucket.getAggregations().get("avg_by_age");
            double value = avg_by_age_result.getValue();
            System.out.println("key:" + keyAsString + "|value:" + value + "|docCount:" + docCount);
        }

    }


}
